<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: schottenland.php 11 2013-09-21 11:43:11Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 11 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2013-09-21 11:43:11 +0000 (Sat, 21 Sep 2013) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

defined( '_VALID_XTC' ) or die( 'Direct Access to this location is not allowed.' );

define('MODULE_SCHOTTENLAND_TEXT_DESCRIPTION', 'Export - Schottenland.de CSV<br><br><b>Info:</b><br>
	Schottenland.de Preisvergleichsportal<br>
	&raquo; <a href="http://anbieter.schottenland.de/?shop=xtc" target="_blank" style="text-decoration:underline">Anmeldung Schottenland.de</a><br>
	F&uuml;r die regelm&auml;&szlig;ige automatische Generierung finden Sie &raquo; <a href="http://anbieter.schottenland.de/exportmodules/export_xtc.zip" target="_blank"><u>hier</u></a> ein Script.<br>
	<br>
	<b>Format:</b><br>
	Bestellnummer, Preis, Produktname, Kategorie, Modell, EAN, Deeplink, Produktbild, Produktbeschreibung, VerfРЎРЉgbarkeitsstatus, Hersteller');
define('MODULE_SCHOTTENLAND_TEXT_TITLE', 'Schottenland.de / HardwareSchotte.de - CSV');
define('MODULE_SCHOTTENLAND_FILE_TITLE' , '</b>Bitte beachten Sie, dass HANs aus dem Produktfeld "Products Model" ausgelesen werden!<hr noshade><b>Dateiname');
define('MODULE_SCHOTTENLAND_FILE_DESC' , 'Geben Sie einen Dateinamen ein, falls die Exportdatei am Server gespeichert werden soll.<br>(Verzeichnis export/)');
define('MODULE_SCHOTTENLAND_STATUS_DESC','Modulstatus');
define('MODULE_SCHOTTENLAND_STATUS_TITLE','Status');
define('MODULE_SCHOTTENLAND_CURRENCY_TITLE','W&auml;hrung');
define('MODULE_SCHOTTENLAND_CURRENCY_DESC','Welche W&auml;hrung soll exportiert werden?');
define('EXPORT_YES','Speichern und herunterladen');
define('EXPORT_NO','Am Server Speichern');
define('CURRENCY','<hr noshade><b>W&auml;hrung:</b>');
define('CURRENCY_DESC','W&auml;hrung in der Exportdatei');
define('EXPORT','Bitte den Sicherungsprozess AUF KEINEN FALL unterbrechen. Dieser kann einige Minuten in Anspruch nehmen.');
define('EXPORT_TYPE','<hr noshade><b>Speicherart:</b>');
define('EXPORT_STATUS_TYPE','<hr noshade><b>Kundengruppe:</b>');
define('EXPORT_STATUS','Bitte w&auml;hlen Sie die Kundengruppe, die Basis f&uuml;r den exportierten Preis bildet. (Falls Sie keine Kundengruppenpreise haben, w&auml;hlen Sie <i>Gast</i>):</b>');
define('CAMPAIGNS','<hr noshade><b>Kampagnen:</b>');
define('CAMPAIGNS_DESC','Mit Kampagne zur Nachverfolgung verbinden.');

class schottenland {
    var $code, $title, $description, $enabled, $db;


    function __construct() {
		global $order, $db;

		$this->code = 'schottenland';
		$this->img = 'images/export/schottenland.gif';
		$this->title = MODULE_SCHOTTENLAND_TEXT_TITLE;
		$this->description = MODULE_SCHOTTENLAND_TEXT_DESCRIPTION;
		$this->enabled = ((MODULE_SCHOTTENLAND_STATUS == 'True') ? true : false);
		$this->db = $db;
    }


    function process($file) {

        set_time_limit(0);
        require(DIR_FS_CATALOG.DIR_WS_CLASSES.'class.price.php');
        $price = new price($_POST['currencies'],$_POST['status'], $this->db);

		$languages_id = 1;
		$lang = $this->db->db_query("SELECT languages_id FROM ".TABLE_LANGUAGES." WHERE  code='".DEFAULT_LANGUAGE."'");

		if($lang->_numOfRows > 0)
			$languages_id = $lang->fields['languages_id'];

		if($_REQUEST['languages_id'] > 0)
			$languages_id = $_REQUEST['languages_id'];

	    $schema = '"Bestellnummer";"Preis";"Produktname";"Kategorie";"Modell";"EAN";"Deeplink";"Produktbild";"Produktbeschreibung";"VerfРЎРЉgbarkeitsstatus";"Hersteller"'."\n";
	    $products = $this->db->db_query("SELECT
											p.products_id,
											pd.products_name,
											pd.products_description,
											p.brand_model,
											p.products_ean,
											p.products_image,
											p.products_shippingtime,
											p.products_price,
											p.products_status,
											p.products_discount_allowed,
											p.products_tax_class_id,
											p.products_date_added,
											m.brand_name,
											c2p.categories_id
										FROM
											".TABLE_PRODUCTS." p
												LEFT JOIN
													".TABLE_BRAND." m
														ON p.brand_id = m.brand_id
												LEFT JOIN
													".TABLE_PRODUCTS_DESCRIPTION." pd
														ON p.products_id = pd.products_id
										AND
											pd.language_id = '".$languages_id."'
												LEFT JOIN
													".TABLE_SPECIALS." s
														ON p.products_id = s.products_id
												LEFT JOIN
													".TABLE_PRODUCTS_TO_CATEGORIES." c2p
														ON p.products_id = c2p.products_id
										WHERE
											p.products_status = 1
										GROUP BY
											p.products_id
										ORDER BY
											p.products_date_added DESC,
											pd.products_name");

	// build categoryMatrix
	$categorie = $this->db->db_query("SELECT
											cat.categories_id,
											cat.parent_id,
											catdesc.categories_name
										FROM
											".TABLE_CATEGORIES." as cat
				    							LEFT JOIN ".TABLE_CATEGORIES_DESCRIPTION." as catdesc
				    								ON cat.categories_id = catdesc.categories_id
				    					WHERE
				    						catdesc.language_id = '".$languages_id."'");
	while(!$categorie->EOF) {
		$categoryMatrix[$categorie->fields['categories_id']] = $categorie_data;
		$categorie->MoveNext();
	}



        while (!$products->EOF) {

            $products_price = $price->GetPrice($products->fields['products_id'], false, 1, $products->fields['products_tax_class_id']);

            $products_description = $products->fields['products_description'];

             $product_category_id = $products->fields['categories_id'];
             $category_names = array();
             do {
             	$category_names[] = $categoryMatrix[$product_category_id]['categories_name'];
         		$product_category_id = $categoryMatrix[$product_category_id]['parent_id'];
             }
             while($product_category_id > 0);
             	$category_string = implode(' > ', array_reverse($category_names));

            //create content
		if($products->fields['products_image']=='')
			$schottenland_image="";
		else
			$schottenland_image=HTTP_CATALOG_SERVER.DIR_WS_CATALOG_THUMBNAIL_IMAGES.$products->fields['products_image'];

            //create content
            $schema .=
                       '"'.$products->fields['products_id'].'";' .
                       '"'.number_format($products_price,2,'.',''). '";'.
                       '"'.schottenland::_sanitizeCvsString($products->fields['products_name']).'";'.
                       '"'.schottenland::_sanitizeCvsString($category_string).'";'.
                       '"'.schottenland::_sanitizeCvsString($products->fields['brand_model']).'";'.
                       '"'.$products->fields['products_ean'].'";'.
                       '"'.HTTP_CATALOG_SERVER.DIR_WS_CATALOG.'product_info.php?'.$_POST['campaign'].product_link($products->fields['products_id'], $products->fields['products_name']).'";' .
                       '"'.$schottenland_image.'";'.
                       '"'.schottenland::_sanitizeCvsString($products_description, true).'";'.
                       '"'.schottenland::_sanitizeCvsString($products->fields['products_shippingtime']).'";'.
                       '"'.schottenland::_sanitizeCvsString($products->fields['brand_name']).'"'."\n";



			$products->MoveNext();
        }
        // create File
          $fp = fopen(DIR_FS_DOCUMENT_ROOT.'export/'.$file, "w+");
          fputs($fp, $schema);
          fclose($fp);


      switch ($_POST['export']) {
        case 'yes':
            // send File to Browser
            $extension = substr($file, -3);
            $fp = fopen(DIR_FS_DOCUMENT_ROOT.'export/'.$file,"rb");
            $buffer = fread($fp, filesize(DIR_FS_DOCUMENT_ROOT.'export/'.$file));
            fclose($fp);
            header('Content-type: application/x-octet-stream');
            header('Content-disposition: attachment; filename='.$file);
            echo $buffer;
            exit;

        break;
        }

    }

    function _sanitizeCvsString($str, $normalizeLinebreaks = false) {
    	$str = strip_tags($str);
    	$str = trim($str);
    	if ($normalizeLinebreaks) {
    		$str = preg_replace('~[\a\e\f\t \0]+~', " ", $str);
    		$str = preg_replace('~[\r\n]+~', " ", $str);
    	} else {
    		$str = preg_replace('~\s+~', " ", $str);
    	}
    	$str = addcslashes($str, '"');
    	return $str;
    }

    function display() {

		$customers_statuses_array = get_customers_statuses();

		$curr='';
		$currencies = $this->db->db_query("SELECT code FROM ".TABLE_CURRENCIES);
	    while(!$currencies->EOF) {
	    	$curr .= draw_radio_field('currencies', $currencies_data->fields['code'],true).$currencies_data->fields['code'].'<br />';
	    	$currencies->MoveNext();
	    }

	    $campaign_array = array(array('id' => '', 'text' => TEXT_NONE));
		$campaign = $this->db->db_query("SELECT campaigns_name, campaigns_refID FROM ".TABLE_CAMPAIGNS." ORDER BY campaigns_id");

		while(!$campaign->EOF) {
			$campaign_array[] = array ('id' => 'refID='.$campaign->fields['campaigns_refID'].'&', 'text' => $campaign->fields['campaigns_name']);
			$campaign->MoveNext();
		}

		return array('text' =>  EXPORT_STATUS_TYPE.'<br>'.
		                      	EXPORT_STATUS.'<br>'.
		                      	draw_pull_down_menu('status',$customers_statuses_array, '1').'<br>'.
		                        CURRENCY.'<br>'.
		                        CURRENCY_DESC.'<br>'.
		                        $curr.
		                        CAMPAIGNS.'<br>'.
		                        CAMPAIGNS_DESC.'<br>'.
		                      	draw_pull_down_menu('campaign',$campaign_array).'<br>'.
		                        EXPORT_TYPE.'<br>'.
		                        EXPORT.'<br>'.
		                      	draw_radio_field('export', 'no',true).EXPORT_NO.'<br>'.
		                        draw_radio_field('export', 'yes',false).EXPORT_YES.'<br>'.
		                        '<br>'.button(BUTTON_EXPORT) .
		                        button_link(BUTTON_CANCEL, href_link(FILENAME_MODULE_EXPORT, 'set='.$_GET['set'].'&module=schottenland')).'<hr noshade>' .
		                        '&raquo; <a href="'.HTTP_CATALOG_SERVER.DIR_WS_CATALOG.'export/schottenland.csv" style="font-weight:bold">Standardlink zum Export</a><br>'.
		                        '&raquo; <a href="http://anbieter.schottenland.de" target="_blank" style="font-weight:bold">Anmeldung Schottenland.de</a>');


    }

    function check() {
		if (!isset($this->_check)) {
			$check = $this->db->db_query("SELECT configuration_value from ".TABLE_CONFIGURATION." WHERE configuration_key = 'MODULE_SCHOTTENLAND_STATUS'");
			$this->_check = $check->_numOfRows;
		}
		return $this->_check;
    }

    function install() {
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value,  configuration_group_id, sort_order, set_function, date_added) VALUES ('MODULE_SCHOTTENLAND_FILE', 'schottenland.csv',  '6', '1', '', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value,  configuration_group_id, sort_order, set_function, date_added) VALUES ('MODULE_SCHOTTENLAND_STATUS', 'Aktiviert',  '6', '1', 'cfg_select_option(array(\'Aktiviert\', \'Deaktiviert\'), ', now())");
	}

    function remove() {
		$this->db->db_query("DELETE FROM ".TABLE_CONFIGURATION." WHERE configuration_key in ('".implode("', '", $this->keys())."')");
    }

    function keys() {
		return array('MODULE_SCHOTTENLAND_STATUS','MODULE_SCHOTTENLAND_FILE');
    }
}
?>